import os
import mimetypes
from binaryornot.check import is_binary
import subprocess

def write_to_file(value):
    with open('../api.txt', 'a') as the_file:
        the_file.write(value)
        the_file.write('\n')
        the_file.close()

def write_to_file_raw(value):
    with open('../api_raw.txt', 'a') as the_file:
        the_file.write(value)
        the_file.write('\n')
        the_file.close()

def parse_file(filepath):
    with open(filepath) as fp:
        line = fp.readline()
        cnt = 1
        while line:
                #if line.count('/') > 1:
                #print("Line {}: {}".format(cnt, line.strip()))
            if line.find('/api/') != -1:
                print filepath
                print cnt
                write_to_file('=============================================================')
                write_to_file(str(filepath))
                write_to_file(str(cnt))
                write_to_file(str(line.strip()))
                write_to_file('=============================================================')
                write_to_file_raw(str(line.strip()))
            line = fp.readline()
            cnt += 1

def parse2_file(filepath):
    print filepath
    cmd = "python EndPoint-Finder.py -f "+filepath+ " >"+filepath+".FE"
    cmdout = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True).communicate()[0]
    print(cmdout)

def search_files(directory='.', extension=''):
    extension = extension.lower()
    for dirpath, dirnames, files in os.walk(directory):
        for name in files:
            if extension and name.lower().endswith(extension):
                filename = os.path.join(dirpath, name)
                if not is_binary(filename):
                    #print filename
                    parse_file(filename)
            elif not extension:
                filename = os.path.join(dirpath, name)
                if not is_binary(filename):
                    #print filename
                    parse2_file(filename)
search_files()
